package ejb;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import model.Candidate;
import model.Citizen;
import model.Governor;
import utils.AbstractBean;
import entitymanagers.CheckingManager;

@Stateless
@LocalBean
public abstract class CheckingManagerBean extends AbstractBean<Citizen> implements CheckingManager {

	@Resource
	private SessionContext context;
	
	@PersistenceContext
	private EntityManager em;
	
	@EJB
	private TimeManager tm;
	
	public CheckingManagerBean() {
		super(Citizen.class);
	}

	@Override
	public boolean canVote() {
		return tm.areVotesEnabled();
	}

	@Override
	public boolean alreadyVoted() {
		Citizen citizen = find(context.getCallerPrincipal().getName());
		if (citizen != null){
			return citizen.getVote() != null;
		}
		return true;
		
	}


	@Override
	public boolean canSubscribe() {
		if (!tm.areAcceptsEnabled()){
			return false;
		}
		else{
			return true;
		}
	}

	

	@Override
	public boolean endVoting() {
		return tm.areElectionsEnded();
	}

	@Override
	public boolean setGovernor() {
		return em.find(Governor.class, context.getCallerPrincipal().getName()) != null;
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}

}
